<?php

namespace app\adminapi\controller;

use app\model\LinkModel;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use Webman\Http\Request;

class Link extends BaseAdminApi
{
    protected $dataModel = LinkModel::class;
    protected array $with = [];
    protected array $allowSearch = ['title', 'url', 'status', 'type'];

    /**
     * 获取广告详情
     */
    public function getBannerDetail(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'id' => v::stringType()->notEmpty()->setName('广告ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $banner = LinkModel::find($params['id']);

            if (!$banner) {
                return $this->fail('广告不存在');
            }

            return $this->success('获取广告详情成功', $banner);
        } catch (\Exception $e) {
            return $this->fail('获取广告详情失败：' . $e->getMessage());
        }
    }

    /**
     * 保存广告
     */
    public function save(Request $request)
    {
        $data = $request->post();

        // 数据验证
        $validationResult = $this->validateBannerData($data);
        if ($validationResult !== true) {
            return $this->fail($validationResult);
        }

        try {
            $bannerData = $this->prepareBannerData($data);
            $banner = $this->saveBanner($data, $bannerData);

            return $this->success('保存成功', $banner);
        } catch (\Exception $e) {
            return $this->fail('保存广告失败，请稍后重试');
        }
    }

    /**
     * 验证广告数据
     * @param array $data
     * @return true|string true表示验证通过，string表示错误信息
     */
    private function validateBannerData(array $data)
    {
        // 验证必填字段
        $requiredFields = [
            'title' => '广告标题不能为空',
            'url' => '跳转链接不能为空',
            'cover_img' => '广告图片不能为空'
        ];

        foreach ($requiredFields as $field => $message) {
            if (empty($data[$field])) {
                return $message;
            }
        }

        // 验证字段长度
        $lengthValidations = [
            'title' => ['max' => 10, 'message' => '广告标题不能超过10个字符'],
            'url' => ['max' => 255, 'message' => '跳转链接不能超过255个字符'],
            'cover_img' => ['max' => 255, 'message' => '图片链接不能超过255个字符']
        ];

        foreach ($lengthValidations as $field => $validation) {
            if (mb_strlen($data[$field]) > $validation['max']) {
                return $validation['message'];
            }
        }

        // 验证跳转类型
        $type = isset($data['type']) ? (int)$data['type'] : 1;
        if (!in_array($type, [1, 2, 3])) {
            return '跳转类型无效';
        }

        // 当类型为外部小程序时，验证appId
        if ($type == 2) {
            if (empty($data['app_id'])) {
                return '外部小程序AppId不能为空';
            }
            if (mb_strlen($data['app_id']) > 50) {
                return 'AppId不能超过50个字符';
            }
        }

        return true;
    }

    /**
     * 准备广告数据
     * @param array $data
     * @return array
     */
    private function prepareBannerData(array $data): array
    {
        $type = isset($data['type']) ? (int)$data['type'] : 1;

        return [
            'title' => trim($data['title']),
            'url' => trim($data['url']),
            'cover_img' => trim($data['cover_img']),
            'type' => $type,
            'app_id' => $type == 2 ? trim($data['app_id']) : null,
            'updated_at' => date('Y-m-d H:i:s'),
        ];
    }

    /**
     * 保存广告数据
     * @param array $data
     * @param array $bannerData
     * @return LinkModel
     */
    private function saveBanner(array $data, array $bannerData): LinkModel
    {
        if (!empty($data['id'])) {
            // 更新现有记录
            $banner = LinkModel::find($data['id']);
            if ($banner) {
                $banner->update($bannerData);
                return $banner;
            } else {
                // ID不存在，创建新记录
                return LinkModel::create(array_merge($bannerData, [
                    'created_at' => date('Y-m-d H:i:s')
                ]));
            }
        } else {
            // 创建新记录
            return LinkModel::create(array_merge($bannerData, [
                'created_at' => date('Y-m-d H:i:s')
            ]));
        }
    }

    /**
     * 删除广告
     */
    public function deleteBanner(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'id' => v::stringType()->notEmpty()->setName('广告ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $banner = LinkModel::find($params['id']);

            if (!$banner) {
                return $this->fail('广告不存在');
            }

            $banner->delete();

            return $this->success('删除广告成功');
        } catch (\Exception $e) {
            return $this->fail('删除广告失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除广告
     */
    public function batchDeleteBanners(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'ids' => v::arrayType()->notEmpty()->each(v::intVal()->min(1))->setName('广告ID列表'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $deleteCount = LinkModel::whereIn('id', $params['ids'])->delete();

            return $this->success('批量删除成功', ['deleted_count' => $deleteCount]);
        } catch (\Exception $e) {
            return $this->fail('批量删除失败：' . $e->getMessage());
        }
    }
}
